<?php

class MySql {

	private $conn = null;
	static $instance = null;

	private function __construct($host, $user, $pass, $dbname) {
		$this->conn = mysql_connect($host, $user, $pass);
		mysql_select_db($dbname);
	}

	private function __clone() {
		;
	}

	public static function getInstance($host, $user, $pass, $dbname) {
		if (!(self::$instance instanceof self)) {
			self::$instance = new self($host, $user, $pass, $dbname);
		}
		return self::$instance;
	}

	public function escape($string){
		return mysql_escape_string($string);
	}

	public function errno(){
		return mysql_errno($this->conn);
	}

	public function error(){
		return mysql_error($this->conn);
	}

	public function query($sql) {
		return mysql_query($sql, $this->conn);
	}

	public function fetch_assoc($res) {
		return mysql_fetch_assoc($res);
	}

	public function getAll($sql, $mode = MYSQL_ASSOC) {
		$data = array();
		$res = $this->query($sql);
		while($data[] = mysql_fetch_array($res, $mode))
			;
		return $data;
	}

	public function getOne($sql){
		$res = $this->query($sql);
		return mysql_fetch_assoc($res);
	}

	public function insert($table, $data) {
		$sql = $this->buildInsertSql($table, $data);
		return $this->query($sql);
	}

	public function update($table, $data, $id){
		$sql = $this->buildUpdateSql($table, $data, $id);
		return $this->query($sql);
	}

	private function buildUpdateSql($table, $data, $id){
		$fields = array();
		foreach($data as $k => $v){
			if(is_numeric($v)){
				$fields[] =  "`{$k}`={$v}";
			}else{
				$v = mysql_escape_string($v);
				$fields[] =  "`{$k}`='{$v}'";
			}
		}
		return "UPDATE {$table} SET " . implode(",", $fields) . " WHERE `id`={$id}";
	}

	private function buildInsertSql($table, $data) {
		$keys = $values = array();
		foreach ($data as $k => $v) {
			$keys[] = "`{$k}`";
			if(is_numeric($v)){
				$values[] = $v;
			}else{
				$v = mysql_escape_string($v);
				$values[] = "'{$v}'";
			}
		}
		return "INSERT INTO {$table} ( " . implode(',', $keys) . " ) VALUES ( " . implode(',', $values) . " )";
	}

	public function __destruct() {
		mysql_close($this->conn);
	}

}